package zhttp

import (
	"context"
	"fmt"
	"net/http"
	"sync"
)

func NewServer(ctx context.Context, config SerConfig) *Server {
	return &Server{
		ctx:    ctx,
		config: config,
		ser:    nil,
		router: new(Router),
	}
}

// AddRoute 添加路由
//
//	ser.AddRoute([]Route{
//	    {"GET", "/hello1", Hello1},
//	    {"GET", "/hello2", Hello2},
//	})
func (ser *Server) AddRoute(routes []Route) {
	for _, route := range routes {
		ser.router.Handle(route)
	}
}

// AddMiddlewareRoute 添加带中间件的路由
//
//	ser.AddMiddlewareRoute([]Middleware{
//	    MiddlewareHello1,
//	    MiddlewareHello2,
//	}, []Route{
//
//	    {"GET", "/hello1", Hello1},
//	    {"GET", "/hello2", Hello2},
//	})
//
// 顺序:MiddlewareHello1(MiddlewareHello2(HandlerFunc()))
func (ser *Server) AddMiddlewareRoute(middlewares []Middleware, routes []Route) {
	ser.AddRoute(MiddlewareRoutes(middlewares, routes))
}

// Start 启动
func (ser *Server) Start(wg *sync.WaitGroup) {
	wg.Add(1)
	go func() {
		wg.Done()

		addr := ser.config.Addr

		ser.ser = &http.Server{
			Addr:    addr,
			Handler: ser.router,
		}

		if err := ser.ser.ListenAndServe(); err != http.ErrServerClosed {
			fmt.Println("Start.ser.ser.ListenAndServe", err.Error())
			return
		}
	}()
}

func (ser *Server) Close() {
	err := ser.ser.Shutdown(context.Background())
	if err != nil {
		fmt.Println("ShutDown.err.Error", err.Error())
	}
}
